package com.yf.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*********************************************************
 ** es 配置信息类
 ** <br><br>
 ** @author: yangfeng
 ** @date: 2023/12/20 14:57
 ** @version: 1.0.0
 *********************************************************/
@Configuration
public class EsConfig {
    @Value("${esastic.host:192.168.2.111}")
    private String http;
    @Value("${esastic.port:32000}")
    private Integer port;
    @Value("${esastic.username:elastic}")
    private String userName;
    @Value("${esastic.password:elastic}")
    private String password;

    @Bean(name = "highClient", destroyMethod = "close")
    public RestHighLevelClient client() {
        //es验证账号密码
        final CredentialsProvider provider = new BasicCredentialsProvider();

        //填写账号密码
        provider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(http, port, "http"))
                        .setHttpClientConfigCallback(httpClientBuilder -> {
                            httpClientBuilder.disableAuthCaching();
                            return httpClientBuilder.setDefaultCredentialsProvider(provider);
                        })
                        .setRequestConfigCallback(requestConfigBuilder -> {
                            return requestConfigBuilder.setConnectTimeout(5000 * 1000) // 连接超时（默认为1秒）
                                    .setSocketTimeout(6000 * 1000);// 套接字超时（默认为30秒）
                        }));

    }

}
